﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.IO;
using Utility;
using System.Configuration;

namespace HaiFang
{
    /// <summary>
    /// Summary description for ModuleInfoHandler
    /// </summary>
    partial class DocumentInfoHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
                  

            if (!String.IsNullOrEmpty(context.Request.QueryString["action"]))
            {
                string action = context.Request.QueryString["action"];
                switch (action)
                {
                    case "GetFolderTree":
                        {
                            string Params = context.Request.QueryString["Params"];
                            ResponseGetFolderTree(context, Params);
                        }
                        break;
                    case "GetFolderInfo":
                        {
                            string Params = context.Request.QueryString["Params"];
                            string KeyWord = context.Request.QueryString["KeyWord"];
                            ResponseGetFolderInfo(context, Params, KeyWord);
                        }
                        break;
                    case "GetDirectoryInfo":
                        {
                            string Params = context.Request.QueryString["Params"];
                            ResponseGetDirectoryInfo(context, Params);
                        }
                        break;
                    case "GetFileInfo":
                        {
                            string Params = context.Request.QueryString["Params"];
                            ResponseGetFileInfo(context, Params);
                        }
                        break;
                    case "UploadFiles":
                        {
                            //模拟用户
                            string windowUser = Security.Decrypt(ConfigurationManager.AppSettings["Usr"].ToString());
                            string windowDomain = Security.Decrypt(ConfigurationManager.AppSettings["Domain"].ToString());
                            string windowPwd = Security.Decrypt(ConfigurationManager.AppSettings["Pwd"].ToString());
                            Impersonate.SetUser(windowUser, windowDomain, windowPwd);

                            HttpPostedFile postFile = context.Request.Files["fileInput"];
                            object oParams = context.Request.Form["Params"];
                            string Params = (oParams != null) ? HttpUtility.UrlDecode(oParams.ToString()) : string.Empty;
                            ResponseUploadFiles(context, Params, postFile);
                        }
                        break;
                    case "DownloadFiles":
                        {
                            //模拟用户
                            string windowUser = Security.Decrypt(ConfigurationManager.AppSettings["Usr"].ToString());
                            string windowDomain = Security.Decrypt(ConfigurationManager.AppSettings["Domain"].ToString());
                            string windowPwd = Security.Decrypt(ConfigurationManager.AppSettings["Pwd"].ToString());
                            Impersonate.SetUser(windowUser, windowDomain, windowPwd);
                            object ofilepath = context.Request.QueryString["filepath"];
                            string filepath = (ofilepath != null) ? HttpUtility.UrlDecode(ofilepath.ToString()) : string.Empty;
                            object ofilename = context.Request.QueryString["filename"];
                            string filename = (ofilename != null) ? HttpUtility.UrlDecode(ofilename.ToString()) : string.Empty;
                            ResponseDownloadFiles(context, filepath, filename);
                        }
                        break;
                    case "CreateFolder":
                        {
                            string Params = context.Request.QueryString["Params"];
                            ResponseCreateFolder(context, Params);
                        }
                        break;
                    case "SearchFiles":
                        {
                            string Params = context.Request.QueryString["Params"];
                            string Keyword = context.Request.QueryString["Keyword"];
                            ResponseSearchDBFiles(context, Params, Keyword);
                        }
                        break;
                    default:
                        WebHelper.WriteJsonError(context, "未知的操作.");
                        break;
                }
            }
            else if (context.Request.Form.Count > 0)
            {
                string action = context.Request.Form["action"];
                switch (action)
                {
                    case "SyscDocumentInfo":
                        {
                            //模拟用户
                            string windowUser = Security.Decrypt(ConfigurationManager.AppSettings["Usr"].ToString());
                            string windowDomain = Security.Decrypt(ConfigurationManager.AppSettings["Domain"].ToString());
                            string windowPwd = Security.Decrypt(ConfigurationManager.AppSettings["Pwd"].ToString());
                            Impersonate.SetUser(windowUser, windowDomain, windowPwd);

                            string Params = context.Request.Form["Params"];
                            //if (!string.IsNullOrEmpty(Params))
                            {
                                ResponseSyscDocumentInfo(context, Params);
                            }
                        }
                        break;
                    case "OcrDocumentInfo":
                        {
                            string Params = context.Request.Form["Params"];
                            if (!string.IsNullOrEmpty(Params))
                            {
                                ResponseOcrDocumentInfo(context, Params);
                            }
                        }
                        break;
                    case "CheckDocumentInfo":
                        {
                            //模拟用户
                            string windowUser = Security.Decrypt(ConfigurationManager.AppSettings["Usr"].ToString());
                            string windowDomain = Security.Decrypt(ConfigurationManager.AppSettings["Domain"].ToString());
                            string windowPwd = Security.Decrypt(ConfigurationManager.AppSettings["Pwd"].ToString());
                            Impersonate.SetUser(windowUser, windowDomain, windowPwd);
                            string FilePath = context.Request.Form["FilePath"];
                            string FileType = context.Request.Form["FileType"];
                            if (!string.IsNullOrEmpty(FilePath) && !string.IsNullOrEmpty(FileType))
                            {
                                ResponseCheckDocumentInfo(context, FilePath,FileType);
                            } 
                        }
                        break;
                    case "DeleteDocumentInfo":
                        {
                            //模拟用户
                            string windowUser = Security.Decrypt(ConfigurationManager.AppSettings["Usr"].ToString());
                            string windowDomain = Security.Decrypt(ConfigurationManager.AppSettings["Domain"].ToString());
                            string windowPwd = Security.Decrypt(ConfigurationManager.AppSettings["Pwd"].ToString());
                            Impersonate.SetUser(windowUser, windowDomain, windowPwd);
                            string FileType = context.Request.Form["FileType"];
                            string AutoID = context.Request.Form["AutoID"];
                            if (!string.IsNullOrEmpty(FileType) && !string.IsNullOrEmpty(AutoID))
                            {
                                ResponseDeleteDocumentInfo(context, FileType, AutoID);
                            }
                        }
                        break;
                    default:
                        WebHelper.WriteJsonError(context, "未知的操作.");
                        break;
                }
            }
        }

        private void ResponseGetFolderTree(HttpContext context, string Params)
        {
            try
            {
                IList<DocumentFolder> list = ProxyDocumentInfo.QueryDocumentFolder(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID());
                WebHelper.WriteJsonResult(context, list);
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
                WebHelper.WriteJsonError(context, null);
            }
        }

        private void ResponseGetFolderInfo(HttpContext context, string Params, string KeyWord)
        {
            try
            {
                IList<DocumentInfo> list = null;
                if (String.IsNullOrEmpty(KeyWord))
                {
                    list = ProxyDocumentInfo.QueryDocumentInfo(WebHelper.GetCurrentUserID(),
                        WebHelper.GetCurrentUserProjectID(), Convert.ToInt32(Params), 2, string.Empty, 1, 0);
                }
                else
                {
                    //search
                    list = ProxyDocumentInfo.QueryDocumentInfo(WebHelper.GetCurrentUserID(),
                        WebHelper.GetCurrentUserProjectID(), Convert.ToInt32(Params), 1, KeyWord, 1, 0);
                }
                WebHelper.WriteJsonResult(context, list);
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
                WebHelper.WriteJsonError(context, null);
            }
        }

        private void ResponseSearchDBFiles(HttpContext context, string path, string Keyword)
        {
            List<CustomDirectoryInfo> arr = new List<CustomDirectoryInfo>();
            try
            {
                int FolderID = 0;
                string sitesRoot = ProxyDocumentInfo.GetProjectDisk(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID());
                ProxyDocumentInfo.QueryDocumentFolderID(WebHelper.GetCurrentUserID(),
                    WebHelper.GetCurrentUserProjectID(), string.Format("{0}{1}\\", sitesRoot, path), out FolderID);
                if (FolderID > 0)
                {
                    IList<DocumentInfo> list = ProxyDocumentInfo.QueryDocumentInfo(WebHelper.GetCurrentUserID(),
                        WebHelper.GetCurrentUserProjectID(), FolderID, 1, Keyword, 1, 0);
                    if (list != null && list.Count > 0)
                    {
                        foreach (DocumentInfo item in list)
                        {
                            int intFileType = ProxyDocumentInfo.GetDocumentFileType(item.FileExt);
                            if (intFileType != 7)
                            {
                                arr.Add(new CustomDirectoryInfo()
                                {
                                    NodeName = item.FileName,
                                    FullName = item.FilePath.Substring(sitesRoot.Length),
                                    NodeType = intFileType
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
            WebHelper.WriteJsonResult(context, arr.ToArray());
        }

        private void ResponseSearchFiles(HttpContext context, string path, string Keyword)
        {
            try
            {
                string sitesRoot = ProxyDocumentInfo.GetProjectDisk(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID());
                DirectoryInfo theFolder = new DirectoryInfo(sitesRoot + path);
                if (!theFolder.Exists) { WebHelper.WriteJsonError(context, "检索目录不存在！"); return; }
                List<CustomDirectoryInfo> arr = new List<CustomDirectoryInfo>();
                PrivateSearchFiles(theFolder, ref arr, Keyword, sitesRoot);
                WebHelper.WriteJsonResult(context, arr.ToArray());
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
                WebHelper.WriteJsonError(context, null);
            }
        }

        private void PrivateSearchFiles(DirectoryInfo theFolder, ref List<CustomDirectoryInfo> arr, string keyWord, string sitesRoot)
        {
            FileInfo[] fileInfo = theFolder.GetFiles();
            foreach (FileInfo item in fileInfo)
            {
                if ((item.Name).ToUpper().Contains(keyWord.ToUpper()))
                {
                    int typeIndex = item.Name.LastIndexOf(".");
                    string fileType = item.Name.Substring(typeIndex + 1, item.Name.Length - typeIndex - 1);
                    int intFileType = ProxyDocumentInfo.GetDocumentFileType(fileType);
                    if (intFileType == 7)
                    {
                        continue;
                    }
                    arr.Add(new CustomDirectoryInfo() { NodeName = item.Name, FullName = item.FullName.Substring(sitesRoot.Length), NodeType = intFileType });
                }
            }
            DirectoryInfo[] dirInfo = theFolder.GetDirectories();
            foreach (DirectoryInfo item in dirInfo)
            {
                PrivateSearchFiles(item, ref arr, keyWord, sitesRoot);
            }
        }

        private void ResponseCreateFolder(HttpContext context, string sfilepath)
        {
            string sitesRoot = ProxyDocumentInfo.GetProjectDisk(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID());
            DirectoryInfo theFolder = new DirectoryInfo(sitesRoot + sfilepath);
            if (theFolder.Exists)
                WebHelper.WriteJsonError(context, "此文件夹已经存在！");
            else
            {
                theFolder.Create();
                WebHelper.WriteJsonResult(context, true);
            }

        }

        private void ResponseDownloadFiles(HttpContext context, string sfilepath, string sfilename)
        {
            string sitesRoot = ProxyDocumentInfo.GetProjectDisk(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID());
            string filepath = sitesRoot + sfilepath;
            FileInfo DownloadFile = new FileInfo(filepath);//path为文件路径.
            if (!DownloadFile.Exists)
            {
                WebHelper.WriteJsonError(context, "下载的文件不存在！");
                return;
            }
            //string Extension = string.Empty;
            //if (DownloadFile.Exists)
            //{
            //    Extension = DownloadFile.Extension;
            //}
            //string filename = string.Format("{0}{1}", sfilename, Extension);
            context.Response.Clear();
            context.Response.ClearHeaders();
            context.Response.Buffer = false;
            context.Response.ContentType = "application/octet-stream";
            context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DownloadFile.Name));
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            context.Response.WriteFile(DownloadFile.FullName);
            context.Response.Flush();
            context.Response.End();
        }

        private void ResponseUploadFiles(HttpContext context, string Params, HttpPostedFile postFile)
        {
            try
            {
                string sitesRoot = ProxyDocumentInfo.GetProjectDisk(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID());
                UploadFileType uf = null;
                JavaScriptSerializer jss = new JavaScriptSerializer();
                HttpPostedFile file = postFile;
                //string fileType = file.FileName.Substring(file.FileName.LastIndexOf('.'));
                string fileName = file.FileName;

                if (!String.IsNullOrEmpty(Params))
                {
                    uf = jss.Deserialize<UploadFileType>(Params);
                }
                if (uf != null)
                {
                    /*if ((postFile != null && postFile.ContentLength > 0))//删除已经存在的同名文件
                    {
                        string delPath=string.Empty;
                        if (!String.IsNullOrEmpty(uf.Name))
                            delPath = sitesRoot + uf.UploadPath + "\\" + uf.Name + fileType;
                        else
                            delPath = sitesRoot + uf.UploadPath + "\\" + file.FileName;
                        if (File.Exists(delPath))
                        {
                            File.Delete(delPath);
                        }
                    }
                    string fileName = String.IsNullOrEmpty(uf.Name) == true ? file.FileName : uf.Name + fileType;*/
                    if (file != null)
                    {
                        if (!System.IO.Directory.Exists(sitesRoot + uf.UploadPath))
                        {
                            System.IO.Directory.CreateDirectory(sitesRoot + uf.UploadPath);
                        }
                        //如果文件已经存在则提示错误
                        string filePath = string.Format("{0}{1}\\{2}", sitesRoot, uf.UploadPath, fileName);
                        FileInfo existFile = new FileInfo(filePath);//path为文件路径.
                        if (existFile.Exists)
                        {
                            context.Response.Write("{\"result\":false}");
                            return;
                        }
                        file.SaveAs(filePath);
                        ProxyDocumentInfo.UploadDocumentInfo(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID(), filePath);
                    }
                    context.Response.Write("{\"result\":true}");
                    return;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
                context.Response.Write("{\"result\":false}");
            }
        }

        private void ResponseGetFileInfo(HttpContext context, string Params)
        {
            try
            {
                string sitesRoot = ProxyDocumentInfo.GetProjectDisk(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID());
                DirectoryInfo theFolder = new DirectoryInfo(sitesRoot + Params);//F:\HaiFangTest\
                if (!theFolder.Exists)
                { WebHelper.WriteJsonError(context, "不存在此目录！"); return; }
                DirectoryInfo[] dirInfo = theFolder.GetDirectories();
                List<CustomDirectoryInfo> arr = new List<CustomDirectoryInfo>();
                foreach (DirectoryInfo item in dirInfo)
                {
                    arr.Add(new CustomDirectoryInfo() { NodeName = item.Name, FullName = item.FullName.Substring(sitesRoot.Length), NodeType = 1 });
                }
                FileInfo[] fileInfo = theFolder.GetFiles();
                foreach (FileInfo item in fileInfo)
                {
                    int typeIndex = item.Name.LastIndexOf(".");
                    string fileType = item.Name.Substring(typeIndex + 1, item.Name.Length - typeIndex - 1);
                    int intFileType = ProxyDocumentInfo.GetDocumentFileType(fileType);
                    if (intFileType == 7)
                    {
                        continue;
                    }
                    arr.Add(new CustomDirectoryInfo() { NodeName = item.Name, FullName = item.FullName.Substring(sitesRoot.Length), NodeType = intFileType });
                }
                WebHelper.WriteJsonResult(context, arr.ToArray());
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
                WebHelper.WriteJsonError(context, null);
            }
        }

        private void ResponseGetDirectoryInfo(HttpContext context, string Params)
        {
            try
            {
                string sitesRoot = ProxyDocumentInfo.GetProjectDisk(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID());

                DirectoryInfo theFolder = new DirectoryInfo(sitesRoot + Params);
                if (!theFolder.Exists)
                { WebHelper.WriteJsonError(context, "不存在此目录！"); return; }
                DirectoryInfo[] dirInfo = theFolder.GetDirectories();
                List<CustomDirectoryInfo> arr = new List<CustomDirectoryInfo>();
                foreach (DirectoryInfo item in dirInfo)
                {
                    arr.Add(new CustomDirectoryInfo() { NodeName = item.Name, FullName = item.FullName.Substring(sitesRoot.Length), NodeType = 1 });
                }
                WebHelper.WriteJsonResult(context, arr.ToArray());
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
                WebHelper.WriteJsonError(context, null);
            }
        }

        private void ResponseSyscDocumentInfo(HttpContext context, string Params)
        {
            try
            {
                //if (!String.IsNullOrEmpty(Params))
                {
                    ProxyDocumentInfo.SynchronismDocument(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID());
                    WebHelper.WriteJsonResult(context, null);
                    return;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
            WebHelper.WriteJsonError(context, null);
        }

        private void ResponseOcrDocumentInfo(HttpContext context, string Params)
        {
            try
            {
                int ErrorMSG = -1;
                DocumentOcrTaskRequest r = null;
                if (!String.IsNullOrEmpty(Params))
                {
                    r = JsonHelper.JsonDeserialize<DocumentOcrTaskRequest>(Params);
                    if (r != null)
                    {
                        ErrorMSG = ProxyDocumentOcrTask.InsertDocumentOcrTask(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID(), r);
                        WebHelper.WriteJsonResult(context, ErrorMSG);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
            WebHelper.WriteJsonError(context, null);
        }

        private void ResponseCheckDocumentInfo(HttpContext context, string FilePath,string FileType)
        {
            try
            {
                string sitesRoot = ProxyDocumentInfo.GetProjectDisk(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID());
                int iFileType = Convert.ToInt32(FileType);
                if (iFileType == 1)
                {
                    //文件夹
                    DirectoryInfo ffolder = new DirectoryInfo(sitesRoot + FilePath);
                    if (!ffolder.Exists)
                    {
                        //文件夹不存在
                        WebHelper.WriteJsonResult(context, false);
                        return;
                    }
                }
                else
                {
                    //文档
                    FileInfo dfile = new FileInfo(sitesRoot + FilePath);
                    if (!dfile.Exists)
                    {
                        //文档不存在
                        WebHelper.WriteJsonResult(context, false);
                        return;
                    }
                }
                WebHelper.WriteJsonResult(context, true);
                return;
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
            WebHelper.WriteJsonError(context, null);
        }

        private void ResponseDeleteDocumentInfo(HttpContext context, string FileType, string AutoID)
        {
            try
            {
                int ErrorMsg = 0;
                int iFileType = Convert.ToInt32(FileType);
                if (iFileType == 1)
                {
                    //文件夹
                    ProxyDocumentInfo.DeleteDocumentFolder(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID().ToString(), Convert.ToInt32(AutoID));
                }
                else
                {
                    //文档
                    ProxyDocumentInfo.InsertDocumentInfo(WebHelper.GetCurrentUserID(), WebHelper.GetCurrentUserProjectID().ToString(),3,
                        Convert.ToInt32(AutoID), 0, string.Empty, string.Empty, out ErrorMsg);
                }
                WebHelper.WriteJsonResult(context, ErrorMsg);
                return;
            }
            catch (Exception ex)
            {
                LogHelper.Writelog(LogType.LogType_Error, ex.Message, ex);
            }
            WebHelper.WriteJsonError(context, null);
        }

        [Serializable]
        public class CustomDirectoryInfo
        {
            public string NodeName { get; set; }
            public int NodeType { get; set; }//1 folder 2 document
            public string FullName { get; set; }
        }

        [Serializable]
        public class UploadFileType
        {
            public string Name { get; set; }
            public string UploadPath { get; set; }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}